<template>
  <div class="template-preview-page">
    <el-card shadow="hover">
      <!-- 页面头部 -->
      <div slot="header" class="page-header">
        <div class="header-left">
          <el-button
            @click="$router.go(-1)"
            icon="el-icon-arrow-left"
            type="text"
            class="back-btn"
          >
            返回
          </el-button>
          <h2 class="page-title">模板预览 - {{ template.name }}</h2>
          <el-tag :type="getTemplateTypeTag(template.type)">
            {{ getTemplateTypeText(template.type) }}
          </el-tag>
        </div>
        <div class="header-actions">
          <el-select
            v-model="currentTestDataId"
            placeholder="选择测试数据"
            style="width: 200px"
            @change="loadTestData"
          >
            <el-option
              v-for="item in testDataList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button
            type="primary"
            @click="generateDocument"
            icon="el-icon-download"
          >
            生成文档
          </el-button>
          <el-button
            @click="printPreview"
            icon="el-icon-printer"
          >
            打印
          </el-button>
        </div>
      </div>

      <!-- 预览内容 -->
      <div class="preview-content">
        <template-preview
          :template="template"
          :test-data="currentTestData"
          mode="preview"
          ref="templatePreview"
        />
      </div>

      <!-- 生成选项对话框 -->
      <el-dialog
        title="生成文档选项"
        :visible.sync="generateDialog.visible"
        width="500px"
      >
        <el-form :model="generateDialog.form" label-width="100px">
          <el-form-item label="文档格式">
            <el-radio-group v-model="generateDialog.form.format">
              <el-radio label="word">Word文档</el-radio>
              <el-radio label="pdf">PDF文档</el-radio>
              <el-radio label="html">HTML网页</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="文件名称">
            <el-input
              v-model="generateDialog.form.filename"
              placeholder="请输入文件名称"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="包含数据">
            <el-checkbox-group v-model="generateDialog.form.includes">
              <el-checkbox label="basicInfo">基本信息</el-checkbox>
              <el-checkbox label="testData">测试数据</el-checkbox>
              <el-checkbox label="calculations">计算结果</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="generateDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmGenerate" :loading="generating">
            生成文档
          </el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import TemplatePreview from '@/components/template-designer/TemplatePreview.vue'

export default {
  name: 'TemplatePreviewPage',
  components: {
    TemplatePreview
  },
  data() {
    return {
      // 模板数据
      template: {},
      
      // 测试数据
      testDataList: [],
      currentTestDataId: '',
      currentTestData: {},
      
      // 生成对话框
      generateDialog: {
        visible: false,
        form: {
          format: 'word',
          filename: '',
          includes: ['basicInfo', 'testData', 'calculations']
        }
      },
      generating: false
    }
  },
  created() {
    this.loadTemplate()
    this.loadTestDataList()
  },
  methods: {
    /**
     * 加载模板数据
     */
    loadTemplate() {
      const templateId = this.$route.params.templateId
      if (!templateId) {
        this.$message.error('模板ID不存在')
        this.$router.go(-1)
        return
      }
      
      // 模拟加载模板详情
      this.template = this.getMockTemplateDetail(templateId)
    },
    
    /**
     * 获取模拟模板详情
     */
    getMockTemplateDetail(templateId) {
      // 这里应该从API获取模板详情
      return {
        id: templateId,
        name: '模板预览',
        type: 'record',
        pageSize: 'A4',
        components: [
          {
            id: 'COMP_001',
            type: 'header',
            position: { x: 0, y: 0, width: 794, height: 80 },
            content: {
              title: '工程质量检测报告',
              subtitle: '预览模式',
              showBorder: true
            }
          },
          {
            id: 'COMP_002',
            type: 'text',
            position: { x: 50, y: 100, width: 200, height: 30 },
            content: {
              text: '样品编号：TEST-2024-001',
              fontSize: 12,
              fontWeight: 'normal'
            }
          }
        ]
      }
    },
    
    /**
     * 加载测试数据列表
     */
    loadTestDataList() {
      // 模拟测试数据列表
      this.testDataList = [
        { id: 'data1', name: '测试数据1 - 钢筋拉伸' },
        { id: 'data2', name: '测试数据2 - 混凝土抗压' },
        { id: 'data3', name: '测试数据3 - 综合检测' }
      ]
      
      if (this.testDataList.length > 0) {
        this.currentTestDataId = this.testDataList[0].id
        this.loadTestData()
      }
    },
    
    /**
     * 加载测试数据
     */
    loadTestData() {
      // 模拟加载测试数据
      this.currentTestData = {
        basicInfo: {
          sampleNo: 'TEST-2024-001',
          projectName: '示例工程项目',
          testDate: '2024-01-20'
        },
        groups: [
          {
            groupId: 'GRP001',
            groupName: '样品信息',
            params: {
              sample_no: { value: 'SAMPLE-001' },
              material_type: { value: 'HRB400' },
              diameter: { value: 25 }
            }
          }
        ]
      }
    },
    
    /**
     * 获取模板类型标签样式
     */
    getTemplateTypeTag(type) {
      const tagMap = {
        record: 'primary',
        report: 'success'
      }
      return tagMap[type] || 'info'
    },
    
    /**
     * 获取模板类型文本
     */
    getTemplateTypeText(type) {
      const textMap = {
        record: '原始记录',
        report: '检测报告'
      }
      return textMap[type] || '未知类型'
    },
    
    /**
     * 生成文档
     */
    generateDocument() {
      this.generateDialog.form.filename = `${this.template.name}_${new Date().getTime()}`
      this.generateDialog.visible = true
    },
    
    /**
     * 确认生成文档
     */
    async confirmGenerate() {
      this.generating = true
      try {
        const generateData = {
          templateId: this.template.id,
          testData: this.currentTestData,
          options: this.generateDialog.form
        }
        
        // 调用API生成文档
        // const result = await this.$api.report.generate(generateData)
        
        // 模拟生成成功
        this.$message.success('文档生成成功')
        this.generateDialog.visible = false
        
        // 模拟下载文件
        this.downloadMockFile()
      } catch (error) {
        console.error('生成文档失败:', error)
        this.$message.error('生成文档失败')
      } finally {
        this.generating = false
      }
    },
    
    /**
     * 模拟下载文件
     */
    downloadMockFile() {
      const blob = new Blob(['模拟文件内容'], { type: 'application/octet-stream' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${this.generateDialog.form.filename}.${this.generateDialog.form.format}`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    },
    
    /**
     * 打印预览
     */
    printPreview() {
      window.print()
    }
  }
}
</script>

<style scoped>
.template-preview-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.back-btn {
  margin-right: 10px;
  color: #606266;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.preview-content {
  background: white;
  border-radius: 4px;
  padding: 20px;
  min-height: 600px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 打印样式 */
@media print {
  .page-header,
  .el-card__header {
    display: none !important;
  }
  
  .template-preview-page {
    padding: 0;
    background: white;
  }
  
  .preview-content {
    padding: 0;
    box-shadow: none;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .template-preview-page {
    padding: 15px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .template-preview-page {
    padding: 10px;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions .el-select {
    width: 100% !important;
  }
}
</style>